package com.jzo2o.foundations.handler;

import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.service.HomeService;
import com.jzo2o.foundations.service.IRegionService;
import com.jzo2o.foundations.service.IServeService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class SpringCacheSyncHandler {

    @Resource
    RedisTemplate redisTemplate;
    @Resource
    IRegionService regionService;

    @Resource
    HomeService homeService;
    @Resource
    IServeService serveService;

    @XxlJob(value = "activeRegionCacheSync")
    public void activeRegionCacheSync(){
        log.info(">>>>>>>>开始进行缓存同步，更新已启用区域");

        //删除原有缓存

        String key = RedisConstants.CacheName.JZ_CACHE+"::ACTIVE_REGIONS";
        redisTemplate.delete(key);

        //通过查询开通区域列表进行缓存
        List<RegionSimpleResDTO> regionSimpleResDTOS = regionService.queryActiveRegionList();

        //遍历区域对该区域下的服务类型进行缓存
        regionSimpleResDTOS.forEach(item->{
            //区域id
            Long regionId = item.getId();

            //删除该区域下的首页服务列表
            String serve_type_key = RedisConstants.CacheName.SERVE_ICON + "::" + regionId;
            redisTemplate.delete(serve_type_key);
            homeService.queryServeIconCategoryByRegionIdCache(regionId);
            //更新该区域开启的服务列表缓存
            String serve_key = RedisConstants.CacheName.SERVE+"::" + regionId;
            redisTemplate.delete(serve_key);
            serveService.getByRegionId(regionId);
            //更新首页热门列表配的缓存
            String hotKey = RedisConstants.CacheName.HOT_SERVE+"::" + regionId;
            redisTemplate.delete(hotKey);
            serveService.getHotServeListByRegionId(regionId);
        });
        log.info(">>>>>>>>更新已启用区域完成");
    }

}
